package com.packet.controller;

import com.packet.mapper.DepartmentMapper;
import com.packet.mapper.EmployeeMapper;
import com.packet.pojo.Department;
import com.packet.pojo.Employee;
import com.packet.service.DepartmentService;
import com.packet.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.List;

/**
 * @className:EmployeeController
 * @Author:wallet_packet Date:2023-11-12 11:27
 * @Describe:
 */
@Controller
public class EmployeeController {
    public static Integer initId = 1006;
    @Autowired
    EmployeeService employeeService;
    @RequestMapping("/emps")
    public String list(Model model){
        List<Employee> employees = employeeService.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }


    @Autowired
    DepartmentService departmentService;
    @GetMapping("/emp")
    public String toAddpage(Model model){
        List<Department> departments = departmentService.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }
    /*把信息再保存一遍
    * 因为信息太多，不知道要修改哪一个，就把信息再次存储一遍，同时会再前端判断id是否存在
    * */
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        if (employee.getId()==null) {
            employee.setId(initId);
            initId++;
        }
        employee.setDepartment(departmentService.getDepartmentById(employee.getDepartment().getId()));
        employeeService.save(employee);
        return "redirect:/emps";
    }

    @GetMapping("/empUpdate/{id}")
    public String updateEmp(@PathVariable("id") Integer id ,Model model){
        Employee employee = employeeService.getEmployeeById(id);
        model.addAttribute("employee",employee);
        Collection<Department> departments = departmentService.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/update";
    }


    @PostMapping("/empUpdate")
    public String updateEmpIt(Employee employee){
        employee.setDepartment(departmentService.getDepartmentById(employee.getDepartment().getId()));
        employeeService.update(employee);
        return "redirect:/emps";
    }


    //删除员工
    @GetMapping("/deleteEmp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id){
        employeeService.delete(id);
        return "redirect:/emps";
    }
}
